//
//  HxChatManager.swift
//  Runner
//
//  Created by 123456 on 2023/6/16.
//

import UIKit
import Hyphenate


class HxChatManage: NSObject, EMChatManagerDelegate,FlutterStreamHandler{

  
    
  
    public func register(registrar:FlutterPluginRegistrar) {
        
        let instance = HxChatManage.shared
        let eventChannel = FlutterEventChannel(name: "listenerEvent/event", binaryMessenger: registrar.messenger())
        eventChannel.setStreamHandler(instance)
    }
   

    
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        sink = events
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        sink = nil
        return nil
    }
    
    
    
    
    static let shared = HxChatManage()
    
    var eventChannel:FlutterEventChannel?
    
    var sink:FlutterEventSink?
    
    
    
    
    deinit {
        EMClient.shared().chatManager.remove(self)
    }
    
    
    public func setEventMessage(){
        EMClient.shared().chatManager.add(self, delegateQueue: nil)
    }
    
    
//    list<EMMessage>
    ///收到普通消息,格式:<HDMessage *>
    func messagesDidReceive(_ aMessages: [Any]!) {
        let msg:EMMessage = aMessages.first as! EMMessage
    
//        EMChatTypeChat   = 0,   /*! \~chinese 单聊消息 \~english one to one chat type */
//        EMChatTypeGroupChat,    /*! \~chinese 群聊消息 \~english Group chat type */
//        EMChatTypeChatRoom,
        
        switch msg.chatType {
            
        case EMChatTypeChat:
            messageToDict(message: msg)
            return
        default:
            print("other=========\(msg.body.description)")
            return
        }
        
    }
    
    
    ///收到命令消息,格式:<HDMessage *>，命令消息不存数据库，一般用来作为系统通知，例如留言评论更新，
    ///会话被客服接入，被转接，被关闭提醒
    func cmdMessagesDidReceive(_ aCmdMessages: [Any]!) {
        print("cmdMessagesDidReceive")
        print(aCmdMessages as Any)
    }
    
    /////消息的状态修改，一般可以用来刷新列表，显示最新的状态
    func messageStatusDidChange(_ aMessage: EMMessage!, error aError: EMError!) {
        print("messageStatusDidChange")
        print(aMessage as Any)
        
    }
    
    ///发送消息后，会调用，可以在此刷新列表，显示最新的消息
    func messageAttachmentStatusDidChange(_ aMessage: EMMessage!, error aError: EMError!) {
        print("messageAttachmentStatusDidChange")
        print(aMessage as Any)
        

    }
    
}

extension HxChatManage {
    
    
    func messageToDict(message: EMMessage){
        
        ///消息json
        var messageData = [String: Any]()
        
        messageData["messageId"] = message.messageId
        messageData["conversationId"] = message.conversationId
        messageData["direction"] = message.direction.rawValue
        messageData["from"] = message.from
        messageData["to"] = message.to
        messageData["timestamp"] = message.timestamp
        messageData["localTime"] = message.localTime
        messageData["chatType"] = message.chatType.rawValue
        messageData["status"] = message.status.rawValue
        messageData["isReadAcked"] = message.isReadAcked
        messageData["isNeedGroupAck"] = message.isNeedGroupAck
        messageData["groupAckCount"] = message.groupAckCount
        messageData["isDeliverAcked"] = message.isDeliverAcked
        messageData["isRead"] = message.isRead
        messageData["body"] = messageBody(body: message.body)
        messageData["ext"] = message.ext
        
        
        if sink != nil{
            sink!(messageData)
        }
        
    }
    
//
    ///消息body
    func messageBody(body: EMMessageBody) -> Dictionary<String, Any>{
        
        var messagebody = [String: Any]()
        //文字消息
        if body is EMTextMessageBody {
            let textMsg:EMTextMessageBody = body as! EMTextMessageBody
            messagebody["text"] = textMsg.text
        }
        //视频消息
        else if body is EMVideoMessageBody {
            
        }
        //图片消息
        else if body is EMImageMessageBody {
            
        }
        //文件消息
        else if body is EMFileMessageBody {
            
        }
        //自定义消息
        else if body is EMCustomMessageBody {
            
        }
        ///其它消息（语音<VOICE>，命令<CMD>,位置<LOCATION>）
        else {
            
        }
        
        return messagebody
 
    }
    
    
    
 
}



